/*
 * @Author: 王明明834578987 10266004+wang-mingming-834578987@user.noreply.gitee.com
 * @Date: 2024-09-29 15:43:30
 * @LastEditors: 王明明834578987 10266004+wang-mingming-834578987@user.noreply.gitee.com
 * @LastEditTime: 2024-10-31 10:42:20
 * @FilePath: \ft-apply-admin\publish\publish.js
 * @Description: 编译后直接发布至指定环境
 */
const path = require('node:path')
const fs = require('fs-extra')
const archiver = require('archiver');
const axios = require('axios');
const FormData = require('form-data');
const distDir = path.join(__dirname, '../dist');
const zipFilePath = path.join(__dirname, 'dist.zip');
// 压缩dist目录
function zipDirectory(source, out) {
  return new Promise((resolve, reject) => {
    const output = fs.createWriteStream(out);
    const archive = archiver('zip', {
      zlib: {
        level: 9
      }
    });
    output.on('close', () => {
      console.log(`压缩完成: ${(archive.pointer()/1024/1024).toFixed(2)}M`);
      resolve();
    });
    archive.on('error', (err) => reject(err));
    archive.pipe(output);
    archive.directory(source, false);
    archive.finalize();
  });
}

// 上传压缩文件到服务器
async function uploadFile(filePath, uploadUrl, params) {
  const fileStream = fs.createReadStream(filePath);
  const form = new FormData();
  form.append('file', fileStream);
  Object.entries(params).forEach(([key, value]) => {
    form.append(key, value);
  });
  try {
    const response = await axios.post(uploadUrl, form, {
      headers: {
        ...form.getHeaders(), // 使用FormData提供的headers
      }
    }, );
    console.log('上传成功:', response.data);
  } catch (error) {
    console.error('上传失败:', error.response ? error.response.data : error.message);
  }
}

function deleteZipFile(filePath) {
  fs.unlink(filePath, (err) => {
    if (err) {
      console.error('删除ZIP文件失败:', err);
    } else {
      console.log('ZIP文件已删除');
    }
  });
}
// 主函数
(async function () {
  try {
    const env = process.argv[2]
    const map = {
      test: {
        uploadUrl: "https://app.thinkworldpro.com/newKejian-test/resources/uploadVueResource",
        path: '/designManagement',
        modelName: '产品设计管理',
      },
      uat: {
        uploadUrl: "https://app.thinkworldpro.com/newKejian-pro/resources/uploadVueResource",
        path: '/designManagement-UAT',
        modelName: '(UAT)产品设计管理',
      },
      pro: {
        uploadUrl: "https://app.thinkworldpro.com/newKejian-pro/resources/uploadVueResource",
        path: '/designManagement',
        modelName: '产品设计管理',
      }
    }
    await zipDirectory(distDir, zipFilePath);
    const uploadUrl = map[env].uploadUrl
    // 上传接口
    const params = {
      path: map[env].path,
      modelName: map[env].modelName,
      versionDepict: '版本迭代',
      uploadName: '王明明',
      projectVersion: "1.2.1",
    };
    await uploadFile(zipFilePath, uploadUrl, params);
    deleteZipFile(zipFilePath); // 上传后删除ZIP文件
  } catch (error) {
    console.error('发生错误:', error);
  }
})();
